<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名字" width="100">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="100">
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="100">
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="100">
      </el-table-column>
      <el-table-column prop="parent.name" label="父部门" min-width="100">
      </el-table-column>
      <el-table-column  prop="path" label="部门路径" width="80">
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="80">
        <template scope="scope">
          <span v-if="scope.row.state == 0" style="color: red;">禁用</span>
          <span v-if="scope.row.state == 1">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="描述" width="120">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="block">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>
		<!--工具条-->
<!--		<el-col :span="24" class="toolbar">-->
<!--			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
<!--			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">-->
<!--			</el-pagination>-->
<!--		</el-col>-->

		<!--编辑界面-->
<!--		<el-dialog title="编辑" v-model="saveFormVisible" :close-on-click-modal="false">-->
<!--			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">-->
<!--				<el-form-item label="姓名" prop="name">-->
<!--					<el-input v-model="saveForm.name" auto-complete="off"></el-input>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="性别">-->
<!--					<el-radio-group v-model="saveForm.sex">-->
<!--						<el-radio class="radio" :label="1">男</el-radio>-->
<!--						<el-radio class="radio" :label="0">女</el-radio>-->
<!--					</el-radio-group>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="年龄">-->
<!--					<el-input-number v-model="saveForm.age" :min="0" :max="200"></el-input-number>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="生日">-->
<!--					<el-date-picker type="date" placeholder="选择日期" v-model="saveForm.birth"></el-date-picker>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="地址">-->
<!--					<el-input type="textarea" v-model="saveForm.addr"></el-input>-->
<!--				</el-form-item>-->
<!--			</el-form>-->
<!--			<div slot="footer" class="dialog-footer">-->
<!--				<el-button @click.native="saveFormVisible = false">取消</el-button>-->
<!--				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>-->
<!--			</div>-->
<!--		</el-dialog>-->

		<!--新增界面-->
<!--		<el-dialog title="新增" :visible:sync="saveFormVisible" :close-on-click-modal="false">-->
<!--			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">-->
<!--				<el-form-item label="姓名" prop="name">-->
<!--					<el-input v-model="saveForm.name" auto-complete="off"></el-input>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="state">-->
<!--					<el-radio-group v-model="saveForm.state">-->
<!--&lt;!&ndash;&lt;!&ndash;            <template slot-scope="scope">&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;              <span v-if="scope.row.state==1">启动</span>&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;              <span v-if="scope.row.state==0">禁用</span>&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;            </template>&ndash;&gt;&ndash;&gt;-->
<!--						<el-radio class="radio" :label="1">-->
<!--              <template slot-scope="scope">-->
<!--                <span v-if="scope.row.state==1">启动</span>-->
<!--                <span v-if="scope.row.state==0">禁用</span>-->
<!--              </template>-->
<!--            </el-radio>-->
<!--						<el-radio class="radio" :label="0">-->
<!--              <template slot-scope="scope">-->
<!--                <span v-if="scope.row.state==1">启动</span>-->
<!--                <span v-if="scope.row.state==0">禁用</span>-->
<!--              </template>-->
<!--            </el-radio>-->
<!--					</el-radio-group>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="经理">-->
<!--					<el-input-number v-model="saveForm.manager.id" :min="0" :max="200"></el-input-number>-->
<!--				</el-form-item>-->
<!--        <el-form-item label="父部门">-->
<!--					<el-input-number v-model="saveForm.parent.id" :min="0" :max="200"></el-input-number>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="父部门">-->
<!--					<el-date-picker type="date" placeholder="选择日期" v-model="saveForm.birth"></el-date-picker>-->
<!--				</el-form-item>-->
<!--				<el-form-item label="简介">-->
<!--					<el-input type="textarea" v-model="saveForm.intro"></el-input>-->
<!--				</el-form-item>-->
<!--			</el-form>-->
<!--			<div slot="footer" class="dialog-footer">-->
<!--				<el-button @click.native="saveFormVisible = false">取消</el-button>-->
<!--				<el-button type="primary" @click.native="addSubmit" :loading="saveForm">提交</el-button>-->
<!--			</div>-->
<!--		</el-dialog>-->
    <el-dialog title="编辑页面" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员" prop="manager">
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :key="resetCascader"
                       :options="deptTree"
                       :props="{
                 emitPath:false,
							   checkStrictly: true,
							   label:'name',
							   value:'id',
							   children: 'children'
							}"
                       clearable></el-cascader>
        </el-form-item>
<!--        <el-form-item label="上级部门">-->
<!--        <el-cascader-->
<!--            v-model="saveForm.parent"-->
<!--            :options="deptTree"-->
<!--            @change="handleChange"></el-cascader>-->
<!--        </el-form-item>-->
        <el-form-item label="简介">
          					<el-input type="textarea" v-model="saveForm.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
	// import util from '../../common/js/util'
	// //import NProgress from 'nprogress'
	// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					name: ''
				},
        pageInfo: {
				  rows:[],
          total:0
        },
        query: {
          currentPage: 1,
          pageSize: 10,
          keyword:""
        },
        resetCascader: 0,
        deptTree: [],
        // deptTree: [{
        //   value: '',
        //   label: '',
        //   children: [{
        //     value: '',
        //     label: '',
        //     children: [{
        //       value: '',
        //       label: ''
        //     }, {
        //       value: '',
        //       label: ''
        //     }, {
        //       value: '',
        //       label: ''
        //     }, {
        //       value: '',
        //       label: ''
        //     }],
        employees: [],
				// departments: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列


				saveLoading: false,
				//编辑界面数据


				saveFormVisible: false,//新增界面是否显示
				saveFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				saveForm: {
					name: '',
					state: 0,
					manager: {
					  id:null,
            username:''
          },
          parent: {
					  id:null,
            name:''
          },
          // parent: [1,2],
          path:'',
					intro: ''
				}

			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getDepartments();
			},
      handleSizeChange(val) {
        this.query.pageSize=val;
        this.getDepartments();
      },
			getDepartments() {
				this.listLoading = true;
				//NProgress.start();

				this.$http.post("/department",this.query).then(result=>{
          this.listLoading = false;
          if(result.data.success){
            this.pageInfo.rows=result.data.obj.pageList;

            this.pageInfo.total=result.data.obj.total;
          }else {
            this.$message({
              message: '查询失败',
              type: 'info'
            });
          }
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          console.log(row.id);
          this.$http.delete("/department/"+row.id).then((res) => {
						this.listLoading = false;
						if(res.data.success){

              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.query.currentPage=1;
              this.getDepartments();
            }else {
              this.$message({
                message: '删除失败',
                type: 'info'
              });
            }
						//NProgress.done()
					});
				}).catch(() => {
          this.$message({
            message: '网络出错了',
            type: 'info'
          });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
        this.getEmployees();
        this.getTree();

        console.log(row.path);
        var pss=row.path.split("/");

        console.log(pss)
        var arr=[];
        for (let i = 1; i < pss.length - 1; i++) {
          arr.push(parseInt(pss[i]))
        }
        console.log("bianji")
        console.log(arr);
        this.saveForm = row
        this.saveForm.parent=arr;

        console.log(this.saveForm.parent);
        // var arr=[];
        // this.saveForm.parent=this.saveForm.parent.id
        // console.log(this.saveForm.parent);
        console.log(this.saveForm.path);

			},
      getEmployees(){
			  this.$http.get("/employee").then(res=>{
          console.log("获取所有员工")
          console.log(res.data);
          if(res.data.success){
			      this.employees=res.data.obj;
          }
        })
      },
      getTree(){
			  this.$http.get("/department/tree").then(res=>{
          console.log("tree")
          console.log(res.data.obj);
          if(res.data.success){
			      this.deptTree=res.data.obj;

          }
        })
      },
			//显示新增界面
			handleAdd: function () {
        console.log("xinzen")
				this.saveFormVisible = true;
        this.getEmployees();
        this.getTree();
				this.saveForm = {
          name: '',
          state: 0,
          manager: {
            id:null,
            username:''
          },
          parent: {
            id:null,
            name:''
          },
          intro: ''
        };
				
			},

			//新增
      saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							// this.saveForm = true;
							//NProgress.start();
							// let para = Object.assign({}, this.saveForm);
              console.log("para");
              console.log(this.saveForm.parent.id == null);
              console.log(this.saveForm.parent);
              console.log(typeof(this.saveForm.parent)=="number")
              console.log("aw")
              console.log(typeof(this.saveForm.parent))

              // if(this.saveForm.parent.length==0||this.saveForm.parent.id == null||this.saveForm.parent.id==0){
              if(typeof(this.saveForm.parent)!="number"){
                this.saveForm.parent={
                  id:0
                }
              }else {
                this.saveForm.parent={
                  id:this.saveForm.parent
                }
              }


              // ps = {
              //   id:ps[ps.length-1],
              // };
              // console.log(ps);
              // this.saveForm.parent=ps;


              console.log(this.saveForm.parent);
              // if (this.saveForm.parent.id=null){
              //   this.saveForm.parent.id=0
              // }
              console.log("dwaoihduiwhfuh")
              console.log(this.saveForm.parent.id);
              this.$http.put("/department",this.saveForm).then((res) => {
                console.log(res.data);
                if(res.data.success) {
                  this.saveForm = false;
                  //NProgress.done();
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  // this.saveForm = res.data;
                  this.saveFormVisible = false;
                  this.query.currentPage=1;
                  this.getDepartments();
                }
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          console.log(ids);
          this.$http.patch("/department",ids).then((res) => {
            this.listLoading = false;
            if(res.data.success){

              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.query.currentPage=1;
              this.getDepartments();
            }else {
              this.listLoading = false;
              this.$message({
                message: '删除失败',
                type: 'info'
              });
            }
            //NProgress.done()
          });
				}).catch(() => {
          this.listLoading = false;
				});
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>